package com.common.download;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.Settings;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.common.UIApplication;
import com.common.config.MyApi;
import com.common.download.dialog.UPProgressDialog;
import com.common.download.dialog.UpdateDialog;
import com.common.mvp.BaseMvpActivity;
import com.common.retrofit.RxObserver;
import com.common.retrofit.json.Data;
import com.lsz.atm.BuildConfig;
import com.lsz.atm.R;
import com.lsz.atm.json.CheckUpdate;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.util_code.base.mvp.MvpView;
import com.util_code.base.mvp.RxMvpPresenter;
import com.util_code.download.DownloadException;
import com.util_code.download.DownloadManager;
import com.util_code.download.downinterfaceimpl.SimpleDownLoadCallBack;
import com.util_code.utils.AndroidUtils;
import com.util_code.utils.ApiLevel;
import com.util_code.utils.RxUtils;
import com.util_code.utils.ToastUtils;
import com.util_code.utils.VersionUtils;

import java.io.File;

public class CheckVersionUpdate extends RxMvpPresenter<MvpView> implements VersionUpdatePresent {

    private static int CHECK_VERSION_INSTALL_APK = 0x0800;

    private BaseMvpActivity activity;
    private final MyApi myApi;
    private VersionUpdatePresent.CheckVersionResult checkVersionResult;

    private UPProgressDialog mUpdateProgressDialog;
    private UpdateDialog mUpdataDialog;
    private String mDownLoadApkFolde;
    private String mDownLoadApkFileName;

    public CheckVersionUpdate(BaseMvpActivity activity, VersionUpdatePresent.CheckVersionResult checkVersionResult) {
        this.activity = activity;
        MyApi myApi = UIApplication.getMyAppComponent().retrofitMyApiHelper();
        this.myApi = myApi;
        this.checkVersionResult = checkVersionResult;
    }


    /**
     * 版本检测更新
     */
    @Override
    public void onCheckUpdate() {
//        HashMap<String, String> hashMap = new HashMap<>();
//        hashMap.put("classcode", Constant.ANDROIDVERSION);
        myApi.checkUpdates()
                .compose(RxUtils.<Data<CheckUpdate>>applySchedulersLifeCycle(activity.getMvpView()))
                .subscribe(new RxObserver<Data<CheckUpdate>>() {

                    @Override
                    public void onNext(@NonNull Data<CheckUpdate> checkUpdateData) {
                        if (RxObserver.checkJsonCode(checkUpdateData, true)) {
                            String app_url = "";
                            CheckUpdate checkUpdate = checkUpdateData.data;
                            if (BuildConfig.APP_ENV == 1) {
                                //是否有更新
                                app_url = "https://qianbao-card-android.oss-cn-hangzhou.aliyuncs.com/MerchatAPK/qianbaobrower-test.apk";
                            } else {
                                //是否有更新
                                app_url = checkUpdate.getApk_url();
                            }
                            checkUpdate.setApk_url(app_url);
                            final boolean update = VersionUtils.needUpdate(AndroidUtils.getAppVersionName(), checkUpdate.getLatest_version(), false);
                            final boolean force = VersionUtils.needUpdate(AndroidUtils.getAppVersionName(), checkUpdate.getForce_update_version(), true);
                            if (update && !force) {
                                // APK可选更新
                                checkUpdate.setMandatoryUpdate(false);
                            } else if (update && force) {
                                // APK强制更新
                                checkUpdate.setMandatoryUpdate(true);
                            }
                            if (update || force) {//下载更新
                                onApkDowloadDialog(checkUpdate);
                            } else {//无需下载更新
                                checkVersionResult.versionNoNeedDowload();
                            }
                        } else {
                            checkVersionResult.versionCheckError();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        checkVersionResult.versionCheckError();
                    }
                });
    }

    @Override
    public void onApkDowloadDialog(CheckUpdate checkUpdate) {
        mDownLoadApkFolde = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
        mDownLoadApkFileName = "shanghu_" + checkUpdate.getLatest_version() + ".apk";
        mUpdataDialog = new UpdateDialog();
        mUpdataDialog.setCancelable(false);
        mUpdataDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                mUpdataDialog.setContent(checkUpdate.getVersion_desc().replaceAll("#", "\r\n"));
                if (checkUpdate.isMandatoryUpdate()) {//强制更新
                    mUpdataDialog.hideCancelButton();
                } else {//选择更新

                }
                mUpdataDialog.setConfirmOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mUpdataDialog.dismissAllowingStateLoss();
                        new RxPermissions(activity).request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                .compose(RxUtils.<Boolean>applySchedulersLifeCycle(activity.getMvpView()))
                                .subscribe(new RxObserver<Boolean>() {
                                    @Override
                                    public void onNext(Boolean aBoolean) {
                                        if (aBoolean) {
                                            mUpdateProgressDialog = new UPProgressDialog();
                                            mUpdateProgressDialog.setOnShowListener(new DialogInterface.OnShowListener() {
                                                @Override
                                                public void onShow(DialogInterface dialog) {
                                                    requestDownload(checkUpdate.getApk_url(), mDownLoadApkFolde, mDownLoadApkFileName);
                                                    mUpdateProgressDialog.getDialog().setCanceledOnTouchOutside(false);
                                                }
                                            });
                                            mUpdateProgressDialog.show(activity.getSupportFragmentManager(), "updateprogressdialog");
                                        } else {
                                            ToastUtils.showShortToast("检查到新版本，但您的权限被拒绝，无法使用存储空间，无法下载最新版本。");
                                            checkVersionResult.versionDowloadError();
                                        }
                                    }
                                });
                    }
                });

                mUpdataDialog.setCancelOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mUpdataDialog.dismissAllowingStateLoss();
                        checkVersionResult.versionNoNeedDowload();
                    }
                });
                mUpdataDialog.getDialog().setCanceledOnTouchOutside(false);
            }
        });
        mUpdataDialog.show(activity.getSupportFragmentManager(), "updatadialog");
    }

    @Override
    public void requestDownload(String sUpdateUrl, String downLoadApkFolde, String downLoadApkFileName) {
        DownloadManager.getInstance().download(sUpdateUrl, new File(downLoadApkFolde), downLoadApkFileName, false, new SimpleDownLoadCallBack() {

            @Override
            public void onProgress(long finished, long total, int progress) {
                if (mUpdateProgressDialog != null && mUpdateProgressDialog.isVisible()) {
                    mUpdateProgressDialog.setProgress(progress);
                }
            }

            @Override
            public void onCompleted(File downloadfile) {
                if (ApiLevel.requireOreo()) {
                    //下载结束，安装apk
                    installApp(downLoadApkFolde, downLoadApkFileName);
                } else {
                    AndroidUtils.installApk(new File(downLoadApkFolde, downLoadApkFileName));
                    UIApplication.finishAllActivity();
                }
            }

            @Override
            public void onFailed(DownloadException e) {
                ToastUtils.showLongToast(R.string.start_file_download_error);
                if (mUpdateProgressDialog != null && mUpdateProgressDialog.isVisible()) {
                    mUpdateProgressDialog.dismissAllowingStateLoss();
                }
                checkVersionResult.versionDowloadError();
            }
        });
    }

    @Override
    public void installApp(String downLoadApkFolde, String downLoadApkFileName) {
        @SuppressLint({"NewApi", "LocalSuppress"})
        boolean canbeInstall = AndroidUtils.getContext().getPackageManager().canRequestPackageInstalls();
        if (canbeInstall) {
            AndroidUtils.installApk(new File(downLoadApkFolde, downLoadApkFileName));
            UIApplication.finishAllActivity();
        } else {
            //请求安装未知应用来源的权限
            new RxPermissions(activity).request(Manifest.permission.REQUEST_INSTALL_PACKAGES)
                    .compose(RxUtils.<Boolean>applySchedulersLifeCycle(activity.getMvpView()))
                    .subscribe(new RxObserver<Boolean>() {
                        @Override
                        public void onNext(Boolean aBoolean) {
                            if (aBoolean) {
                                AndroidUtils.installApk(new File(downLoadApkFolde, downLoadApkFileName));
                                UIApplication.finishAllActivity();
                            } else {
                                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + activity.getPackageName()));
                                activity.startActivityForResult(intent, CHECK_VERSION_INSTALL_APK);
                            }
                        }
                    });
        }
    }

    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == activity.RESULT_OK && requestCode == CHECK_VERSION_INSTALL_APK) {
            installApp(mDownLoadApkFolde, mDownLoadApkFileName);
        } else if (resultCode == activity.RESULT_CANCELED && requestCode == CHECK_VERSION_INSTALL_APK) {
            UIApplication.finishAllActivity();
        }
    }

}
